package com.lz.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {
    private DecReceiver decReceiver = new DecReceiver();
    private ArrayList<BluetoothDevice> devices = new ArrayList<>();

    private Button btnScan;
    private BluetoothAdapter bluetooth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        bluetooth = BluetoothAdapter.getDefaultAdapter();
        btnScan = (Button) findViewById(R.id.scan_btn);
        open();
        setFindTime();
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentFilter intentFilter=new IntentFilter();
                intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
                registerReceiver(decReceiver, intentFilter);
                bluetooth.startDiscovery();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (decReceiver!=null){
            unregisterReceiver(decReceiver);
        }
    }

    private void setFindTime() {
        Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
        startActivity(intent);
    }

    private void open() {
        if (bluetooth!=null && !bluetooth.isEnabled()){
            bluetooth.enable();
        }
    }

    public  class DecReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent!=null && intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device = intent.getExtras().getParcelable(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
            }
        }
    }
}
